package com.tanhua.dubbo.api.mongo;

import com.tanhua.commons.exception.TanHuaException;
import com.tanhua.model.mongo.Friend;
import com.tanhua.model.mongo.Sound;
import com.tanhua.model.mongo.Sound;
import com.tanhua.model.vo.ErrorResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Random;
import java.util.Set;

/**
 * 桃花传音接口实现类
 *
 * @author youshengfeng
 * @date 2022/2/20 上午 11:00
 */
@DubboService
public class SoundApiImpl implements SoundApi {
    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 发送语音
     *
     * @param sound
     */
    @Override
    public void addVoice(Sound sound) {
        mongoTemplate.insert(sound);
    }

    /**
     * 随机获取一个语音
     *
     * @param gender         屏蔽的性别
     * @param noFindIds      查找屏蔽的id List集合
     * @param notLikeUserIds 查找屏蔽的id Set集合
     * @param readVoiceIds   已经听过的语音id Set集合
     * @return
     */
    @Override
    public Sound findSound(String gender, List<Long> noFindIds, Set<Long> notLikeUserIds, Set<ObjectId> readVoiceIds) {
        Query query = new Query();
        //设置查询条件屏蔽对应性别
        query.addCriteria(Criteria.where("gender").ne(gender));
        //设置查询条件屏蔽id
        for (Long noFindId : noFindIds) {
            notLikeUserIds.add(noFindId);
        }
        query.addCriteria(Criteria.where("userId").nin(notLikeUserIds));
        //设置查询条件屏蔽已经听过的语音
        query.addCriteria(Criteria.where("id").nin(readVoiceIds));
        List<Sound> sounds = mongoTemplate.find(query, Sound.class);
        //如果查询集合为空 直接返回一个null给消费者
        if (CollectionUtils.isEmpty(sounds)){
            return null;
        }
        Random random = new Random();
        int index = random.nextInt(sounds.size());
        return sounds.get(index);
    }

    /**
     * 跟据语音id 查询语音消息
     *
     * @param id
     * @return
     */
    @Override
    public Sound findVoice(ObjectId id) {
        return mongoTemplate.findById(id, Sound.class);
    }

    /**
     * 根据 用户性别推荐 语音
     *
     * @param findGender
     * @return
     */
    @Override
    public List<Sound> findAllId(String findGender) {
        Query query = new Query();
        query.addCriteria(Criteria.where("gender").is(findGender));
        List<Sound> sounds = mongoTemplate.find(query, Sound.class);
        return sounds;
    }

}
